package com.sparrow.resource.convert.impl;

import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import org.springframework.core.convert.converter.Converter;

/**
 * 字符串转int int map
 * 数据模板 1:2;3:4
 */
public class Int2IntMapConverter implements Converter<String, Int2IntOpenHashMap> {

    @Override
    public Int2IntOpenHashMap convert(String source) {
        Int2IntOpenHashMap map = new Int2IntOpenHashMap();
        if (source == null || source.trim().isEmpty()) {
            return map;
        }

        // 按 ';' 拆分每个键值对
        String[] pairs = source.split(";");
        for (String pair : pairs) {
            if (pair.isEmpty()) continue;

            String[] kv = pair.split(":");
            if (kv.length != 2) continue; // 格式不对则跳过

            int key = Integer.parseInt(kv[0].trim());
            int value = Integer.parseInt(kv[1].trim());
            map.put(key, value);
        }

        return map;
    }
}
